package app.common.utils.history;

import app.common.utils.FormsUtils;
import app.common.utils.IdGenerator;
import app.common.utils.YdApi;
import app.common.utils.cjt.CJtUtils;
import app.common.utils.cjt.ao.OtherReceiveCreateAo;
import com.aliyun.dingtalkyida_1_0.models.GetFormDataByIDResponseBody;
import com.aliyun.dingtalkyida_1_0.models.GetInstanceByIdResponseBody;
import com.gitee.feizns.dynamic.DateUtils;
import com.gitee.feizns.quickstart.jackson.JsonUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

interface TransferYiDaToRK {

    static void main(String[] args) {
//        System.out.println(FormsUtils.getPrice("Y-hya065"));
        rkToYiD("2024-01-01", "2024-01-25");
    }

    /**
     * rk,犹太人
     * @param startDate 开始日期
     * @param endDate 结束日期
     */
    static void rkToYiD(String startDate, String endDate) {
        CJtUtils.resetOpenToken();
        List<String> ids = YdApi.yiDaUtils.forms.instanceIds("FORM-8Y866XB14GP3HMKK6SM90DD382BH2LHD0UJ8LS1",
                startDate,
                endDate);
        //货品入库单
        for (String id : ids) {
            try {
                GetFormDataByIDResponseBody data = YdApi.yiDaUtils.forms.getById(id);
                System.out.println(JsonUtils.toJson(data));
                Map<String, ?> formData = data.getFormData();
                String cg = (String) formData.get("textField_lg0ibky2");
                if ( cg.contains("采购") )
                    continue;
                OtherReceiveCreateAo.Dto dto = new OtherReceiveCreateAo.Dto();
                String no = Objects.toString(formData.get("textField_l8ju1vvl"));
                String code = code(data.getModifiedTimeGMT(), no);
                dto.setExternalCode(code + "-" + no);
                dto.setCode(code);
                dto.setVoucherType(new OtherReceiveCreateAo.Dto.VoucherType("ST1004"));
                dto.setVoucherDate(data.getModifiedTimeGMT());
                dto.setBusiType(new OtherReceiveCreateAo.Dto.BusiType("13"));
                dto.setWarehouse(new OtherReceiveCreateAo.Dto.Warehouse(String.valueOf(formData.get("textField_l8ju1vvj"))));
                dto.setMemo(
                        String.format("来源=[宜搭], 表单=[%s], 单号=[%s], 备注=[%s]， 原单号=[%s]",
                                formData.get("textField_lg0ibky2"),
                                code,
                                formData.get("textField_lidyg2ai"),
                                formData.get("textField_l8ju1vvh")
                                )
                );
                //数据详情
                OtherReceiveCreateAo.Dto.RDRecordDetails details = new OtherReceiveCreateAo.Dto.RDRecordDetails();
                details.setInventory(new OtherReceiveCreateAo.Dto.RDRecordDetails.Inventory(String.valueOf(formData.get("textField_l8ju1vvl"))));
                Object o = formData.get("numberField_l8ju1vvs");
                if ( o != null )
                    details.setAmount(BigDecimal.valueOf(Double.parseDouble(String.valueOf(o))));
                BigDecimal price = FormsUtils.getPrice(no);
                if ( price != null )
                    details.setPrice(price);
                Object baseQuantity = formData.get("numberField_l8ju1vvq");
                if ( baseQuantity != null )
                    details.setBaseQuantity(BigDecimal.valueOf(Double.parseDouble(String.valueOf(baseQuantity))));
                dto.setRDRecordDetailsObj(details);
                try {
                    CJtUtils.otherReceiveCreate(dto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

//        //FORM-EA866E71TB7AY6VB7BWYL5CJIOGC3UCD7D7HLF
//        ids = YdApi.yiDaUtils.processes.getIds("FORM-EA866E71TB7AY6VB7BWYL5CJIOGC3UCD7D7HLF", req -> {
//            req.setModifiedFromTimeGMT(startDate);
//            req.setModifiedToTimeGMT(endDate);
//            req.setInstanceStatus("COMPLETED");
//            req.setApprovedResult("agree");
//        });

        //生产领料入库
        ids = YdApi.yiDaUtils.processes.getIds("FORM-Z2666J810PK2TK7J6G5425QYSMYE2RB2UC66LU4", req -> {
            req.setModifiedFromTimeGMT(startDate);
            req.setModifiedToTimeGMT(endDate);
            req.setInstanceStatus("COMPLETED");
            req.setApprovedResult("agree");
        });

        for (String id : ids) {
            GetInstanceByIdResponseBody instance = YdApi.yiDaUtils.processes.getById(id);
            Map<String, ?> data = instance.getData();
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> o = (List<Map<String, Object>>) data.get("tableField_l57i1a1x");
            for (Map<String, Object> map : o) {
                double baseQuantity = Double.parseDouble(String.valueOf(map.get("numberField_l57i1a1z")));
                if ( baseQuantity <= 0.00001 )
                    return;
                OtherReceiveCreateAo.Dto dto = new OtherReceiveCreateAo.Dto();
                String no = String.valueOf(map.get("textField_l5di70a1"));
                String code = code(instance.getModifiedTimeGMT(), no);
                dto.setExternalCode(code + "-" + no);
                dto.setCode(code);
                dto.setVoucherType(new OtherReceiveCreateAo.Dto.VoucherType("ST1024"));
                dto.setVoucherDate(instance.getModifiedTimeGMT());
                dto.setBusiType(new OtherReceiveCreateAo.Dto.BusiType("13"));
                dto.setWarehouse(new OtherReceiveCreateAo.Dto.Warehouse("038"));
                dto.setMemo(
                        String.format("来源=[宜搭] 表单=[%s] 单号=[%s] 备注：[%s] 原单号：[%s]",
                                "生产领料",
                                code,
                                "领料出库",
                                data.get("serialNumberField_lg7ok4i2"))
                );
                OtherReceiveCreateAo.Dto.RDRecordDetails detail = new OtherReceiveCreateAo.Dto.RDRecordDetails();
                detail.setInventory(new OtherReceiveCreateAo.Dto.RDRecordDetails.Inventory(String.valueOf(no)));
                detail.setBaseQuantity(new BigDecimal(baseQuantity));
                BigDecimal price = FormsUtils.getPrice(no);
                detail.setPrice(price);
                detail.setAmount(price.multiply(new BigDecimal(baseQuantity)));
                dto.setRDRecordDetailsObj(detail);
                try {
                    CJtUtils.otherReceiveCreate(dto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("传输完成...");
        System.out.println("传输完成...");
        System.out.println("传输完成...");
    }

    static String code(String date, String no) {
        LocalDateTime time = DateUtils.parse(date, LocalDateTime.class);
        String key = no + "-" + time;
        return String.format("RK%s%05d", DateUtils.format(time, "yyyyMMddHHmm"), idGenerator.next(key));
    }

    IdGenerator idGenerator = new IdGenerator();

}